package me.zhengjie.modules.zhishiku.service.impl;

import me.zhengjie.modules.zhishiku.domain.TZhishiku;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.zhishiku.repository.TZhishikuRepository;
import me.zhengjie.modules.zhishiku.service.TZhishikuService;
import me.zhengjie.modules.zhishiku.service.dto.TZhishikuDTO;
import me.zhengjie.modules.zhishiku.service.dto.TZhishikuQueryCriteria;
import me.zhengjie.modules.zhishiku.service.mapper.TZhishikuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author jie
* @date 2020-08-03
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TZhishikuServiceImpl implements TZhishikuService {

    @Autowired
    private TZhishikuRepository tZhishikuRepository;

    @Autowired
    private TZhishikuMapper tZhishikuMapper;

    @Override
    public Object queryAll(TZhishikuQueryCriteria criteria, Pageable pageable){
        Page<TZhishiku> page = tZhishikuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tZhishikuMapper::toDto));
    }

    @Override
    public Object queryAll(TZhishikuQueryCriteria criteria){
        return tZhishikuMapper.toDto(tZhishikuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TZhishikuDTO findById(Integer id) {
        Optional<TZhishiku> tZhishiku = tZhishikuRepository.findById(id);
        ValidationUtil.isNull(tZhishiku,"TZhishiku","id",id);
        return tZhishikuMapper.toDto(tZhishiku.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TZhishikuDTO create(TZhishiku resources) {
        return tZhishikuMapper.toDto(tZhishikuRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TZhishiku resources) {
        Optional<TZhishiku> optionalTZhishiku = tZhishikuRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTZhishiku,"TZhishiku","id",resources.getId());

        TZhishiku tZhishiku = optionalTZhishiku.get();
        // 此处需自己修改
        resources.setId(tZhishiku.getId());
        tZhishikuRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        tZhishikuRepository.deleteById(id);
    }
}